package net.zjitc.controller;

import net.zjitc.pojo.Admin;
import net.zjitc.pojo.UpdateAdmin;
import net.zjitc.service.SettingService;
import net.zjitc.utils.APIResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.Objects;

@RestController
@RequestMapping("/setting")
public class SettingController {
    @Autowired
    private SettingService settingService;

    @Value("${file.upload-dir}")
    private String uploadDir;


    @PostMapping("/changePassword")
    @ResponseBody
    public APIResponse<String> changePassword(@RequestBody UpdateAdmin updateAdmin) {
        APIResponse<String> apiResponse = new APIResponse<>();
        int response = settingService.changePassword(
                updateAdmin.getUsername(),
                updateAdmin.getOldPassword(),
                updateAdmin.getNewPassword(),
                updateAdmin.getNewPassword2());
        if (response == 0) {
            apiResponse.success("修改成功", "0");
            return apiResponse;
        } else if (response == 1) {
            apiResponse.fail(1000, "两次输入的密码不一致", "1000");
            return apiResponse;
        } else if (response == 2) {
            apiResponse.fail(1000, "旧密码与新密码相同","1000");
            return apiResponse;
        } else if (response == 3) {
            apiResponse.fail(1000, "旧密码错误", "1000");
            return apiResponse;
        } else {
            apiResponse.fail(1000, "修改失败", "1000");
            return apiResponse;
        }

    }

    @PostMapping("/changeAvatar")
    @ResponseBody
    public APIResponse<Admin> changeAvatar(@RequestBody Admin admin) {
        int admin1 = settingService.changeAvatar(admin.getUsername(),uploadDir + admin.getAvatar());
        APIResponse<Admin> apiResponse = new APIResponse<>();
        try {
            if (admin1 == 1) {
                apiResponse.fail(1000, "修改失败", null);
                return apiResponse;
            }
            apiResponse.success("修改成功", admin);
            return apiResponse;
        } catch (Exception e) {
            apiResponse.fail(1000, "修改失败", null);
            return apiResponse;
        }
    }


}

